var basePath="assets/js/datatable/";
var InitiateSimpleDataTable = function () {
    return {
        init: function () {
            //Datatable Initiating
            var oTable = $('#simpledatatable').dataTable({
                "sDom": "Tflt<'row DTTTFooter'<'col-sm-6'i><'col-sm-6'p>>",
                "iDisplayLength": 5,
                "oTableTools": {
                    "aButtons": [
                        "copy", "csv", "xls", "pdf", "print"
                    ],
                    "sSwfPath": basePath+"assets/swf/copy_csv_xls_pdf.swf"
                },
                "language": {
                    "search": "",
                    "sLengthMenu": "_MENU_",
                    "oPaginate": {
                        "sPrevious": "Prev",
                        "sNext": "Next"
                    }
                },
                "aoColumns": [
                  { "bSortable": false },
                  null,
                  { "bSortable": false },
                  null,
                  { "bSortable": false }
                ],
                "aaSorting": []
            });

            //Check All Functionality
            jQuery('#simpledatatable .group-checkable').change(function () {
                var set = $(".checkboxes");
                var checked = jQuery(this).is(":checked");
                jQuery(set).each(function () {
                    if (checked) {
                        $(this).prop("checked", true);
                        $(this).parents('tr').addClass("active");
                    } else {
                        $(this).prop("checked", false);
                        $(this).parents('tr').removeClass("active");
                    }
                });

            });
            jQuery('#simpledatatable tbody tr .checkboxes').change(function () {
                $(this).parents('tr').toggleClass("active");
            });

        }

    };

}();
var InitiateEditableDataTable = function () {
    return {
        init: function () {
            //Datatable Initiating
            var oTable = $('#editabledatatable').dataTable({
                "aLengthMenu": [
                    [5, 15, 20, 100, -1],
                    [5, 15, 20, 100, "All"]
                ],
                "iDisplayLength": 5,
                "sPaginationType": "bootstrap",
                "sDom": "Tflt<'row DTTTFooter'<'col-sm-6'i><'col-sm-6'p>>",
                "oTableTools": {
                    "aButtons": [
				        "copy",
				        "print",
				        {
				            "sExtends": "collection",
				            "sButtonText": "Save <i class=\"fa fa-angle-down\"></i>",
				            "aButtons": ["csv", "xls", "pdf"]
				        }],
                    "sSwfPath": basePath+"assets/swf/copy_csv_xls_pdf.swf"
                },
                "language": {
                    "search": "",
                    "sLengthMenu": "_MENU_",
                    "oPaginate": {
                        "sPrevious": "Prev",
                        "sNext": "Next"
                    }
                },
                "aoColumns": [
                  null,
                  null,
                  null,
                  null,
                  { "bSortable": false }
                ]
            });

            var isEditing = null;

            //Add New Row
            $('#editabledatatable_new').click(function (e) {
                e.preventDefault();
                var aiNew = oTable.fnAddData(['', '', '', '',
                        '<a href="#" class="btn btn-success btn-xs save"><i class="fa fa-edit"></i> Save</a> <a href="#" class="btn btn-warning btn-xs cancel"><i class="fa fa-times"></i> Cancel</a>'
                ]);
                var nRow = oTable.fnGetNodes(aiNew[0]);
                editRow(oTable, nRow);
                isEditing = nRow;
            });

            //Delete an Existing Row
            $('#editabledatatable').on("click", 'a.delete', function (e) {
                e.preventDefault();

                if (confirm("Are You Sure To Delete This Row?") == false) {
                    return;
                }

                var nRow = $(this).parents('tr')[0];
                oTable.fnDeleteRow(nRow);
                alert("Row Has Been Deleted!");
            });

            //Cancel Editing or Adding a Row
            $('#editabledatatable').on("click", 'a.cancel', function (e) {
                e.preventDefault();
                if ($(this).attr("data-mode") == "new") {
                    var nRow = $(this).parents('tr')[0];
                    oTable.fnDeleteRow(nRow);
                } else {
                    restoreRow(oTable, isEditing);
                    isEditing = null;
                }
            });

            //Edit A Row
            $('#editabledatatable').on("click", 'a.edit', function (e) {
                e.preventDefault();

                var nRow = $(this).parents('tr')[0];

                if (isEditing !== null && isEditing != nRow) {
                    restoreRow(oTable, isEditing);
                    editRow(oTable, nRow);
                    isEditing = nRow;
                } else {
                    editRow(oTable, nRow);
                    isEditing = nRow;
                }
            });

            //Save an Editing Row
            $('#editabledatatable').on("click", 'a.save', function (e) {
                e.preventDefault();
                if (this.innerHTML.indexOf("Save") >= 0) {
                    saveRow(oTable, isEditing);
                    isEditing = null;
                    //Some Code to Highlight Updated Row
                }
            });


            function restoreRow(oTable, nRow) {
                var aData = oTable.fnGetData(nRow);
                var jqTds = $('>td', nRow);

                for (var i = 0, iLen = jqTds.length; i < iLen; i++) {
                    oTable.fnUpdate(aData[i], nRow, i, false);
                }

                oTable.fnDraw();
            }

            function editRow(oTable, nRow) {
                var aData = oTable.fnGetData(nRow);
                var jqTds = $('>td', nRow);
                jqTds[0].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[0] + '">';
                jqTds[1].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[1] + '">';
                jqTds[2].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[2] + '">';
                jqTds[3].innerHTML = '<input type="text" class="form-control input-small" value="' + aData[3] + '">';
                jqTds[4].innerHTML = '<a href="#" class="btn btn-success btn-xs save"><i class="fa fa-save"></i> Save</a> <a href="#" class="btn btn-warning btn-xs cancel"><i class="fa fa-times"></i> Cancel</a>';
            }

            function saveRow(oTable, nRow) {
                var jqInputs = $('input', nRow);
                oTable.fnUpdate(jqInputs[0].value, nRow, 0, false);
                oTable.fnUpdate(jqInputs[1].value, nRow, 1, false);
                oTable.fnUpdate(jqInputs[2].value, nRow, 2, false);
                oTable.fnUpdate(jqInputs[3].value, nRow, 3, false);
                oTable.fnUpdate('<a href="#" class="btn btn-info btn-xs edit"><i class="fa fa-edit"></i> Edit</a> <a href="#" class="btn btn-danger btn-xs delete"><i class="fa fa-trash-o"></i> Delete</a>', nRow, 4, false);
                oTable.fnDraw();
            }

            function cancelEditRow(oTable, nRow) {
                var jqInputs = $('input', nRow);
                oTable.fnUpdate(jqInputs[0].value, nRow, 0, false);
                oTable.fnUpdate(jqInputs[1].value, nRow, 1, false);
                oTable.fnUpdate(jqInputs[2].value, nRow, 2, false);
                oTable.fnUpdate(jqInputs[3].value, nRow, 3, false);
                oTable.fnUpdate('<a href="#" class="btn btn-info btn-xs edit"><i class="fa fa-edit"></i> Edit</a> <a href="#" class="btn btn-danger btn-xs delete"><i class="fa fa-trash-o"></i> Delete</a>', nRow, 4, false);
                oTable.fnDraw();
            }
        }

    };
}();
var InitiateExpandableDataTable = function () {
    return {
        init: function () {
            /* Formatting function for row details */
            function fnFormatDetails(oTable, nTr) {
                var aData = oTable.fnGetData(nTr);
                var sOut = '<table>';
                sOut += '<tr><td rowspan="5" style="padding:0 10px 0 0;"><img src="assets/img/avatars/' + aData[6] + '"/></td><td>Name:</td><td>' + aData[1] + '</td></tr>';
                sOut += '<tr><td>Family:</td><td>' + aData[2] + '</td></tr>';
                sOut += '<tr><td>Age:</td><td>' + aData[3] + '</td></tr>';
                sOut += '<tr><td>Positon:</td><td>' + aData[4] + '</td></tr>';
                sOut += '<tr><td>Others:</td><td><a href="">Personal WebSite</a></td></tr>';
                sOut += '</table>';
                return sOut;
            }

            /*
             * Insert a 'details' column to the table
             */
            var nCloneTh = document.createElement('th');
            var nCloneTd = document.createElement('td');
            nCloneTd.innerHTML = '<i class="fa fa-plus-square-o row-details"></i>';

            $('#expandabledatatable thead tr').each(function () {
                this.insertBefore(nCloneTh, this.childNodes[0]);
            });

            $('#expandabledatatable tbody tr').each(function () {
                this.insertBefore(nCloneTd.cloneNode(true), this.childNodes[0]);
            });

            /*
             * Initialize DataTables, with no sorting on the 'details' column
             */
            var oTable = $('#expandabledatatable').dataTable({
                "sDom": "Tflt<'row DTTTFooter'<'col-sm-6'i><'col-sm-6'p>>",
                "aoColumnDefs": [
                    { "bSortable": false, "aTargets": [0] },
                    { "bVisible": false, "aTargets": [6] }
                ],
                "aaSorting": [[1, 'asc']],
                "aLengthMenu": [
                   [5, 15, 20, -1],
                   [5, 15, 20, "All"]
                ],
                "iDisplayLength": 5,
                "oTableTools": {
                    "aButtons": [
				        "copy",
				        "print",
				        {
				            "sExtends": "collection",
				            "sButtonText": "Save <i class=\"fa fa-angle-down\"></i>",
				            "aButtons": ["csv", "xls", "pdf"]
				        }],
                    "sSwfPath": basePath+"assets/swf/copy_csv_xls_pdf.swf"
                },
                "language": {
                    "search": "",
                    "sLengthMenu": "_MENU_",
                    "oPaginate": {
                        "sPrevious": "Prev",
                        "sNext": "Next"
                    }
                }
            });


            $('#expandabledatatable').on('click', ' tbody td .row-details', function () {
                var nTr = $(this).parents('tr')[0];
                if (oTable.fnIsOpen(nTr)) {
                    /* This row is already open - close it */
                    $(this).addClass("fa-plus-square-o").removeClass("fa-minus-square-o");
                    oTable.fnClose(nTr);
                }
                else {
                    /* Open this row */
                    $(this).addClass("fa-minus-square-o").removeClass("fa-plus-square-o");;
                    oTable.fnOpen(nTr, fnFormatDetails(oTable, nTr), 'details');
                }
            });

            $('#expandabledatatable_column_toggler input[type="checkbox"]').change(function () {
                var iCol = parseInt($(this).attr("data-column"));
                var bVis = oTable.fnSettings().aoColumns[iCol].bVisible;
                oTable.fnSetColumnVis(iCol, (bVis ? false : true));
            });

            $('body').on('click', '.dropdown-menu.hold-on-click', function (e) {
                e.stopPropagation();
            });
        }
    };
}();
var InitiateSearchableDataTable = function () {
    return {
    	init: function(dataTableId,ajaxSourceUrl,aoColumns) {
    		var aSelected = [];//一选中的行
    		var pageSize=[];
    		var pageSizeRemark=[];
    		var i=0;
			pageSize[i]=(i+1)*3;
			pageSizeRemark[i]="显示"+(i+1)*3+"条";
    		for(i++;i<=100;i++){
    			pageSize[i]=i*5;
    			pageSizeRemark[i]="显示"+i*5+"条";
    		}
			pageSize[i]=-1;
			pageSizeRemark[i]="显示所有";
    		var oTable = $('#'+dataTableId).dataTable({
    			sPaginationType: "bootstrap",
    			sDom: "<'pagingBar' <'filterBar'fT>pl>t<'pagingBar' ripl>",
    			aaSorting: [[1, 'asc']],
    			aLengthMenu: [pageSize, pageSizeRemark],
    			iDisplayLength: 10,
    			oTableTools: {
    				aButtons: [{
    					sExtends: "collection",
    					sButtonText: "另存为 <i class=\"fa fa-angle-down\"></i>",
    					aButtons: ["csv", "xls", "pdf", ]
    				},
    				{
    					sExtends: "select_all",
    					sButtonText: "全选"
    				},
    				{
    					sExtends: "select_none",
    					sButtonText: "全不选"
    				}],
    				sSwfPath: basePath + "assets/swf/copy_csv_xls_pdf.swf"
    			},
    			oLanguage: {
    				sSearch: " 列表检索：",
    				sLengthMenu: "_MENU_",
    				sZeroRecords: "抱歉， 没有找到",
    				sInfo: "从 _START_ 到 _END_ /共 _TOTAL_ 条数据 共 <span id='totalPage'></span> 页  " +
    						"第 <input text style='width:30px;text-align: center;' id='nowPageNo'> 页 " +
    						"<a class='btn btn-sm' id='goPage' href='javascript:' style='margin-top: -4px;'>转到 " +
    						"<i class='fa fa-check right'></i>" +
    						"</a>",
    				sInfoEmpty: "没有数据",
    				sInfoFiltered: "(从 _MAX_ 条数据中检索)",
    				oPaginate: {
    					sFirst: "首页",
    					sPrevious: "前一页",
    					sNext: "后一页",
    					sLast: "尾页"
    				},
    				sZeroRecords: "<div style='font-weight: bold;'>没有检索到数据</div>",
    				sProcessing: "<img src='assets/img/loading.gif' />"
    			},
    			bProcessing:true,
    			bStateSave: false,
    			bPaginate: true,
    			bAutoWidth: true,
    			bLengthChange: true,
    			sRowSelect: true,
    			sScrollX: "100%",
    			bScrollCollapse: "110%",
    			bScrollCollapse: true,
    			sServerMethod: "POST",
    			bDestory:true,
    			//Ajax异步从指定当从办事端获取表格数据时，数据项应用的名字,默认是：aaData
    			sAjaxDataProp: "aaData",
    			//指定从服务器端获取数据    
    			bServerSide: true,
    			//获取数据的url
    			sAjaxSource: ajaxSourceUrl,
    			aoColumns: eval("("+aoColumns+")"),
    			sColumns: eval("("+aoColumns+")"),
    			//获取数据的处理函数 
    			"fnServerData": function(sSource, aoData, fnCallback) {
    				var params="";
    				$.each(aoData,function(index,item){
    					params+=item.name+"="+item.value+"&";
    				});
    				params=params.substring(0,params.length-1);
    				//undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined
    				if(/^undefined=undefined(&undefined=undefined)*$/.test(params)){
    					params="";
    					var aoDataStr=JSON.stringify(aoData);
    					 for(var attr in aoData){
				           params+=attr+"="+aoData[attr]+"&";
				        }  
	    				params=params.substring(0,params.length-1);
    				}
    				if (sSource.indexOf("?") > -1) {
    					sSource += "&timer=" + new Date().getTime() + "&" + params;
    				} else {
    					sSource += "?timer=" + new Date().getTime() + "&" + params;
    				}
    				// 将客户名称加入参数数组  
    				$.ajax({
    					type: "POST",
    					contentType: "application/json",
    					url: sSource+params,
    					dataType: "json",
    					data: {},
    					// 以json格式传递  
    					success: function(resp) {
    						fnCallback(resp);
    					},
    					error : function(XMLHttpRequest, textStatus, errorThrown) {
    						alert(errorThrown == "" ? "服务器端异常!" : errorThrown);
    					}
    				});
    			},
    			fnRowCallback: function( nRow, aData, iDisplayIndex ) {
    				if (jQuery.inArray(aData.DT_RowId, aSelected) !== -1 ) {
    					$(nRow).addClass('active');
    				}
    				return nRow;
    			},
    			fnInitComplete:function(oSettings){
    				//附加头部列搜索框
    				var search_engine_table=$(".dataTables_scrollHead").clone();
					var columns=eval("("+aoColumns+")");
					$.each(columns,function(index,item){
						$.each(search_engine_table.find("table thead tr th"),function(i,ite){
							if(index==i){
								var isTimeInput=item.isDate==true ? "timeInput" : "";
								$(this).html('<input type="text" name="search_engine" placeholder="Search '+item.mData+
										'" class="form-control input-sm '+isTimeInput+'" style="width:100%;">');
							}
						});
					});
					search_engine_table.attr("class",dataTableId+"_search");
    				$('#'+dataTableId).parents(".dataTables_scroll").find(".dataTables_scrollHead").before(search_engine_table);
    				//初始化时间端选择文本框
    				$(".timeInput").each(function(i,item){
    					$(item).daterangepicker({
    						maxDate : moment(), //最大时间   
    						dateLimit : {  
    							days : 30  
    						}, //起止时间的最大间隔  
    						format:'YYYY-MM-DD HH:mm:ss',
    						separator:' TO ',//此分隔符请勿随意修改,以免后台代码无法运行
    						opens:'left',
    						showDropdowns : true,
    						showWeekNumbers : false, //是否显示第几周 
    						timePicker : true, //是否显示小时和分钟 
    						timePickerIncrement : 1,//时间的增量，单位为分钟
    						timePicker12Hour:false,
    						locale:{
    							applyLabel:'确认',
    							cancelLabel:'取消',
    							fromLabel:'起始时间',
    							toLabel:'结束时间',
    							customRangeLabel : '自定义',
    							daysOfWeek : [ '日', '一', '二', '三', '四', '五', '六' ],  
    							monthNames : [ '一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月' ],  
    							firstDay : 1
    						},
    						ranges : {  
    							'最近1小时': [moment().subtract('hours',1), moment()],  
    							'今日': [moment().startOf('day'), moment()],  
    							'昨日': [moment().subtract('days', 1).startOf('day'), moment().subtract('days', 1).endOf('day')],  
    							'最近7日': [moment().subtract('days', 6), moment()],  
    							'最近30日': [moment().subtract('days', 29), moment()]  
    						}
    					}, function(start, end, label) {//当选择的时间范围确认后自动检索过滤数据(若选择的时间范围没有改变，不会搜索)
    						oTable.fnFilter(item.value, $("."+dataTableId+"_search input").index(item));
    					}); 
    				});
    			}
    		});
    		//每一列头部搜索
            $(document).on("keydown","."+dataTableId+"_search input",function (event) {
                /* Filter on the column (the index) of this element */
            	if(event.which==13){
            		oTable.fnFilter(this.value, $("."+dataTableId+"_search input").index(this));
            	}
            });
            //单击行选中
            $(document).on('click' , '#'+dataTableId+' tbody tr' , function () {
        		var id = $(this).index('#'+dataTableId+' tbody tr' );
        		var index = jQuery.inArray(id, aSelected);
        		if ( index === -1 ) {
        			aSelected.push( id );
        		} else {
        			aSelected.splice( index, 1 );
        		}
        		$(this).toggleClass('active');
        	});
            //同步每一页显示记录数
            $(document).on("change","[name='searchable_length']",function(){
            	$("[name='searchable_length']").val($(this).val());
            });
        }
    };
}();
